/**
 * Created by zzy on 2016/12/8.
 */
var $ = require('jquery');
require('easyui');
require('layout/uiJs');
var $alert = require("libs/alert");
require('js-path/jquery-validation-wrapper');
var memoValidator = null;
var isSale = require('libs/user-type').isSale;
$(function () {
    var $spans = $('#checkModal .iteam-col1 span');
    var $img = $('#checkModal .iteam-col1 img');
    var $auditSts = $('#checkModal input[name=auditSts]');
    var $id = $('#checkModal input[name=id]');
    var $memoModal = $('#memoModal'),
        $mMemoForm = $('#mMemoForm');
    $(document).on('click','.handler',function (e) {
        var $this = $(this);
        var scene = $this.attr('name');
        if(scene == 'memo'){
            var full = $this.data('full');
            $memoModal.modal('show',{
                id: full.id,
                recommended: full.recommended,
                recommendedCompany: full.recommendedCompany,
                recommendedTel: full.recommendedTel,
                recommendedRemark: full.recommendedRemark
            });
        }else{
            return false;
        }
    });
    $memoModal.on('show.bs.modal',function (e) {
        var rel = e.relatedTarget;
        $mMemoForm.setForm(rel);
    });
    $memoModal.on('hidden.bs.modal',function (e) {
        $mMemoForm.find('input').val('').end().find('textarea').val('');
        memoValidator.resetForm();
    });
    $('#mMemoCommit').on('click',function (e) {
        $mMemoForm.submit();
    });
    memoValidator = $mMemoForm.validateWapper({
        submitHandler: function() {
            var formData = $mMemoForm.serializeObject();
            var notEmpty = false;
            for(var x in formData){
                if(x == 'id'){
                    continue;
                }
                if(formData[x].trim() !== ''){
                    notEmpty = true;
                }
            }
            if(!notEmpty){
                $memoModal.modal('hide');
                return false;
            }
            $.ajax({
                url: 'api/v1/p/mms/ent/editRecommendeInfo',
                type: 'post',
                data: JSON.stringify(formData),
                contentType: 'application/json;charset=utf-8'
            })
                .done(function (res) {
                    if(res.code==200){
                        $memoModal.modal('hide');
                        $('#entTable').datagrid('reload');
                    }else{
                        $alert(res.message);
                    }
                });
        }
    });
    $('#checkModal').on('show.bs.modal',function (e) {
        var button = $(e.relatedTarget);
        var id = button.data('id');
        var module = button.data('module');
        $id.val(id);
        $.get('api/v1/p/crm/enterpriseInfo/load',{id: id},function (res) {
            if(res.code == 200){
                if(module === 'readonly'){
                    fillData(res.data,'readonly');
                }else{
                    fillData(res.data);
                }
            }else{
                $alert(res.message);
            }
        })
    });
    $("#checkModal").on("hidden.bs.modal",function () {
        $('#checkForm').show();
        $spans.text('');
        $img.attr('src','');
        $('#rejectReason').val('').removeAttr("readonly").hide();
        $auditSts.get(0).checked = true;
        $('#mTitle').text('');
        $('#entTable').datagrid('reload');
        $id.val('');
        $('#checkSubmit').show();
    });
    $auditSts.on('change',function () {
       if(this.value === 'P'){
           $('#rejectReason').val('').hide();
       }else{
           $('#rejectReason').show();
       }
    });
    $(document).on('click','a[name=entDetail]',function () {
        window.parent.tabOpen($(this).attr('ref'),'客户公司',true,true);
    });
    /*$(document).on('click','a[name=detail]',function () {
        var id = $(this).data('id');
        $('#checkModal').modal('show', $("<a href='javascript:;' data-toggle='modal' data-target='#checkModal' data-module='readonly' data-id='"+id+"'></a>"));
    });*/
    $('#checkSubmit').on('click',function (e) {
       e.preventDefault();
       var formData = $('#checkForm').serializeObject();
       if(formData.auditSts === 'R'&&formData.rejectReason === ''){
           $alert('请填写审核不通过原因');
           return false;
       }
        $.ajax({
            url: 'api/v1/p/mms/ent/audit',
            type: 'post',
            contentType: 'application/json;charset=utf-8',
            data: JSON.stringify(formData)
        })
            .done(function (res) {
                if(res.code == 200){
                    $("#checkModal").modal('hide');
                }else{
                    $alert(res.message);
                }
            })
    });
    $('#search').on('click',function () {
        $('#entTable').datagrid('load',{
            entName:$('#tb input[name=entName]').val(),
            type:$('#tb input[name=type]').val(),
            auditSts:$('#tb input[name=auditSts]').val(),
            starDate:$('#startDt').data('utc0'),
            endDate:$('#endDt').data('utc0')
        })
    });
    tableInit();
    function fillData(data,module) {
        if(module === 'readonly'){
            $('#checkSubmit').hide();
            if(data.sts === 'P'||data.sts === 'R'){
                if(data.sts === 'P'){
                    $auditSts.get(0).checked = true;
                }else{
                    $auditSts.get(1).checked = true;
                }
                $auditSts.trigger('change');
                $('#rejectReason').val(data.rejectReason).attr('readonly',true);
            }else{
                $('#checkForm').hide();
            }
        }
        var enterBsLicensePath = '';//营业执照
        var enterTaxPath = '';//税务登记证
        var enterOrganCodePath = '';//组织机构代码证
        for(var i=0; i<data.enterPics.length; i++){
            switch(data.enterPics[i].objectType){
                case 'EnterBsLicense': enterBsLicensePath = data.enterPics[i].filePath;break;
                case 'EnterTax': enterTaxPath = data.enterPics[i].filePath;break;
                case 'EnterOrganCode': enterOrganCodePath = data.enterPics[i].filePath;break;
                default: break;
            }
        }
        $('#mTitle').text(data.name);
        $($spans[0]).text(data.linkMan);
        $($spans[1]).text(data.linkPhone);
        $($spans[2]).text(data.linkTel);
        $($spans[3]).text(data.country);
        $($spans[4]).text(data.province+" "+data.city+" "+data.area);
        $($spans[5]).text(data.address);
        $($spans[6]).text(data.zipcode);
        $($spans[7]).text(data.type == 'E'?'企业客户':'个体客户');
        $($spans[8]).text(data.name);
        $($spans[9]).text(data.linkmanDuty);
        $($spans[10]).text(data.qq);
        $($spans[11]).text(data.email);
        $($spans[12]).text(data.fax);
        $($spans[13]).text(data.emergencyLinkMan);
        $($spans[14]).text(data.emergencyLinkTel);
        $($spans[15]).text(data.saleEmail);
        $($spans[16]).text(data.busiLicense);
        $($img[0]).attr('src',enterBsLicensePath);
        $($img[1]).attr('src',enterTaxPath);
        $($img[2]).attr('src',enterOrganCodePath);//'static/images/Certificates-1.png'
    }
    function tableInit() {
        $('#entTable').datagrid({
            url:'api/v1/p/mms/ent/list',
            border : false,
            height:$(window).height(),
            pagination : true,
            pageSize : 20,
            pageList : [ 20, 50,  100 ],
            emptyMsg : "暂无数据",
            singleSelect: true,
            rownumbers:true,
            columns:[[
                {
                    field:'entName',
                    title:'客户名称',
                    width:'25%',
                    formatter:function (value,row,index) {
                        return "<a class='ellipsis' href='javascript:;' ref='company-detail?id="+row.id+"' name='entDetail' title='"+value+"'>"+value+"</a>";
                    }
                },{
                    field:'type',
                    title:'开户类型',
                    width:'10%',
                    formatter:function (value,row,index) {
                        switch (value){
                            case 'E': return '企业客户';
                            case 'P': return '个人客户';
                            default: return '';
                        }
                    }
                },
                {
                    field:'submitDt',
                    title:'备案时间',
                    width:'20%'
                },{
                    field:'submitBy',
                    title:'备案用户',
                    width:'25%',
                    formatter:function (value,row,index) {
                        return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                    }
                },{
                    field:'auditSts',
                    title:'审核状态',
                    width:'10%',
                    formatter:function (value,row,index) {
                        switch (value){
                            case 'C': return '未审核';
                            case 'P': return '审核通过';
                            case 'R': return '审核失败';
                            default: return '';
                        }
                    }
                },{
                    field:'opt',
                    title:'操作',
                    hidden:isSale,
                    width:'10%',
                    formatter:function (value,row,index) {
                        var ret = "<a class='handler' href='javascript:;' name='memo' data-full='"+JSON.stringify(row)+"'>备注</a>";
                        if(row.auditSts == 'C'){
                            ret += '|<a href="javascript:;" data-toggle="modal" data-target="#checkModal" data-id="'+row.id+'"><i class="glyphicon glyphicon-pencil"></i>审核</a>'
                        }
                        return ret;
                    }
                }
            ]],
            loadFilter:function(data){
                if(data.code == '200'){
                    return data.data;
                }else{
                    return [];
                }
            },
            toolbar:"#tb"
        });
    }
});
